package com.boarsoft.boar.deploy.app.biz;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.app.biz.AppBaseBizImpl;
import com.boarsoft.boar.deploy.app.AppDeployBiz;
import com.boarsoft.boar.deploy.entity.AppDeployInfo;
import com.boarsoft.boar.entity.AppInfo;
import com.boarsoft.boar.entity.DirInfo;
import com.boarsoft.boar.entity.FileInfo;
import com.boarsoft.boar.file.FileBiz;

@Component("appDeployBiz")
public class AppDeployBizImpl extends AppBaseBizImpl implements AppDeployBiz {
	@Autowired
	protected FileBiz fileBiz;

	@Override
	@Transactional(readOnly = true)
	public AppInfo get(String id) {
		AppDeployInfo o = dao.get(AppDeployInfo.class, id);
		dao.evict(o);
		// o.setFiles(null);
		// o.setInsts(null);
		// o.setLibs(null);
		return o;
	}

	@Override
	@Transactional
	public void delete(String id) {
		super.delete(id);
		// 删除应用本身
		dao.delete(AppDeployInfo.class, id);
	}

	/**
	 * 拷贝应用 1，需要在app_info表复制拷贝一条 2，需要在app_lib表复制拷贝一条 3，需要在app_file表复制拷贝一条
	 * 4，需要在app_inst表复制拷贝一条 5，需要在dir_info表复制拷贝一条
	 *
	 * @param sourceId
	 * @param parentId
	 * @param newId
	 * @return
	 */
	@Override
	@Transactional
	public String copy(String sourceId, String parentId, String newId) {
		AppInfo o = this.get(sourceId);
		AppInfo n = this.transfer(o, AppInfo.class);
		n.setId(newId);// //应用的id来自于前一步骤的dir_info表id
		DirInfo pd = dirBiz.get(parentId);
		String projId = dirBiz.lookup(pd, DirInfo.TYPE_PROJ);
		n.setProjId(projId);
		dao.save(n);
		Set<FileInfo> oldFiles = o.getFiles();
		if (oldFiles != null && oldFiles.size() > 0) {
			for (FileInfo file : oldFiles) {
				fileBiz.copy(file.getId(), parentId, newId);
			}
		}
		appLibBiz.copy(sourceId, newId);
		// appFileBiz.copy(sourceId, newId);
		appInstBiz.copy(sourceId, newId);
		return newId;
	}
}